$(document).ready(function () {
  $('.close_icon').hide();
  $('.modal-dialog-bg,.modal-dialog').hide();

  $('.label-input-label').on("input", function () {
    // 如果输入框中有内容，显示删除按钮
    if ($(this).val().length > 0) {
      $('.close_icon').show();
    } else {  // 否则隐藏删除按钮
      $(".close_icon").hide();
    }
  });

  // 给输入框绑定 keydown 事件
  $('.label-input-label').on('keydown', (event) => {
    if (event.keyCode === 13) {
      alert_preview();
    }
  });

  // 如果1秒内没有按键盘, 则搜索
  var debounceTimer = null; // 定义一个防抖动计时器
  $('.label-input-label').on('input', function () {
    clearTimeout(debounceTimer); // 清除之前的计时器
    debounceTimer = setTimeout(function () {
      alert_preview();
    }, 1000); // 设置1秒后执行相应操作
  });


  $('.close_icon').click(function () {
    $(this).hide();
    $('#preview_results').hide();
    $('#preview_results_none').hide();
    $('.create-alert-div-down').hide();
    $(".label-input-label").val('').focus();
  });


  $('.create_button').on('click', function () {
    let kw = $('.label-input-label').val().trim();

    // 发送删除请求
    $.ajax({
      url: '/alert/upsertAlert',
      type: 'POST',
      data: {
        kw: kw
      },
      success: function (response) {
        window.location.reload();
      },
      error: function (jqXHR, textStatus, errorThrown) {
        // 请求失败后的处理逻辑
        console.error('新增失败', textStatus, errorThrown);
      }
    });
  })


  $('.delete_button').on('click', function () {
    // 获取data-id属性值
    const kw = $(this).closest('.alert_instance').data('kw');

    // 发送删除请求
    $.ajax({
      url: '/alert/deleteAlert',
      type: 'POST',
      data: {
        kw: kw
      },
      success: function (response) {
        $(`.alert_instance[data-kw="${kw}"]`).remove();
        $('#alert-counter').text(+$('#alert-counter').text() - 1);
        window.Alert.show({title: '本条快讯已删除'}, 2000);
      },
      error: function (jqXHR, textStatus, errorThrown) {
        // 请求失败后的处理逻辑
        console.error('删除失败', textStatus, errorThrown);
      }
    });
  });


  $('.user_settings_trigger').on('click', function () {
    $('.modal-dialog-bg,.modal-dialog').show();
  })


  $('#save-delivery-hour').on('click', function () {
    let delivery_hours = $('input[name="hours[]"]:checked').map(function() {
      return this.value;
    }).get();

    console.log(delivery_hours);

    $.ajax({
      url: '/alert/updateDeliveryHours',
      type: 'POST',
      data: {
        delivery_hours: delivery_hours
      },
      success: function (response) {
        $('.modal-dialog-bg,.modal-dialog').hide();
        window.Alert.show({title: '修改递送时间成功'}, 2000);
      }
    });
  })


  $('#close-delivery-hour').on('click', function () {
    $('.modal-dialog-bg,.modal-dialog').hide();
  })


  function alert_preview() {
    $('#preview_results').hide();
    $('#preview_results_none').hide();
    $('.create-alert-div-down').hide();

    let kw = $('.label-input-label').val().trim();
    if (!kw) {
      return;
    }

    $('#preview_loading_div').show();

    $.get(`/alert/preview?kw=${kw}`, function (resp) {
      $('#preview_loading_div').hide();
      $('.create-alert-div-down').show();
      const data = resp.data;
      if (data.length > 0) {
        $('#preview_results').show();
        $('.result_set_on_source').empty();
        for (let i = 0; i < data.length; i++) {
          const item = data[i];
          $('.result_set_on_source')
            .append(`<li class="result"><h4 class="result_title"><a class="result_title_link" href="${item.original_url}" target="_blank">${item.title}</a><div class="result_source">${item.author_name}</div></h4><div><span class="snippet">${item.intro}</span></div></li>`);
        }
      } else {
        $('#preview_results_none').show();
      }
    });
  }
});

